from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core import serializers
from django.http import JsonResponse
from Login import models
from Login.models import Notification
from Login.service import Login as log, verify
from django.views.decorators.http import require_POST
import json
from django.contrib.sessions.models import Session
from django.views.decorators.csrf import csrf_exempt
from .form import update_user_informationModelForm, alter_passwordModelForm
import datetime


# Create your views here.

# 注册
@require_POST
@csrf_exempt
def register(request):
    post_data = request.body
    data = json.loads(post_data)
    user_name = data.get("user_name")
    password = data.get('password')
    phone = data.get('phone')
    email = data.get('email')
    code = data.get('code')
    # 这里是字典
    msg = log.userRegister(user_name=user_name, password=password, phone=phone, email=email, code=code)
    # 这里取到字典里面的具体值
    msg = msg.get("msg")
    # print(type(msg))
    if msg == "注册成功":
        return JsonResponse({"code": 200, "msg": msg})
    else:
        return JsonResponse({"code": 404, "msg": msg})


# 登录
@require_POST
@csrf_exempt
def login(request):
    post_data = request.body
    data = json.loads(post_data)
    phone = data.get("phone")
    password = data.get("password")

    msg = log.userLogin(phone=phone, password=password)  # 这里获取的是字典
    if msg.get("msg") == "登录成功":
        sessionId = log.setSession(request=request, phone=phone, password=password)
        data = msg.get("data")
        msg_ = msg.get("msg")
        return JsonResponse({"code": 200, "msg": msg_, "data": data, "sessionId": sessionId})
    else:
        # 要返回值，而不是字典，故这里不应该返回msg，而是应该用get方法获取指定的值
        return JsonResponse({"code": 404, "msg": msg.get("msg")})


# 发送验证码
@require_POST
@csrf_exempt
def sendCode(request):
    try:
        post_data = request.body
        data = json.loads(post_data)
        email = data.get('email')
    except json.JSONDecodeError:
        email = request.POST.get('email')

    if not email:
        return JsonResponse({"code": 400, "msg": "请填写邮箱地址"})

    msg = verify.sendMessageByEmail(email=email)
    if msg == "验证码发送成功":
        return JsonResponse({'code': 200, 'msg': msg})
    elif msg == "请不要一分钟之内连续获取两次验证码":
        return JsonResponse({'code': 404, 'msg': msg})
    else:
        return JsonResponse({'code': 404, 'msg': msg})


# 获取session
@require_POST
def getSession(request):
    try:
        post_data = request.body
        data = json.loads(post_data)
        sessionId = data.get("sessionId")
    except json.JSONDecodeError:
        sessionId = request.POST.get("sessionId")

    session = Session.objects.get(session_key=sessionId)
    sessionData = session.get_decoded()

    isLogin = sessionData.get("isLogin", False)
    if isLogin:
        userData = log.getSessionReturnUserData1(sessionData=sessionData)

        return JsonResponse({"code": 200, "msg": "你已经登录", "data": userData})
    else:
        return JsonResponse({"code": 404, "msg": "请先登录", "data": ""})


# 清除session
@require_POST
def clearSession(request):
    try:
        post_data = request.body
        data = json.loads(post_data)
        sessionId = data.get("sessionId")
    except json.JSONDecodeError:
        sessionId = request.POST.get("sessionId")

    print(sessionId)
    try:
        # 从数据库中删除session
        Session.objects.get(session_key=sessionId).delete()
        return JsonResponse({"code": 200, "msg": "成功清除session"})
    except Exception as e:
        print(e)
        return JsonResponse({"code": 404, "msg": "清除session失败"})


# 我的通知

# 通知列表
@login_required
def notification_list(request):
    all_notification = Notification.objects.filter(recipient_id=request.user_id)
    return JsonResponse({'code': 200, 'msg': '成功', 'date': all_notification})


# 查看接受的通知
def look_notification(request):
    recipient_id = request.POST.get("user_id")
    sender_id = request.POST.get("sender_id")
    try:
        notification = Notification.objects.get(sender_id=sender_id, recipient_id=recipient_id)
        notification.is_read = True
        notification.save()
        return JsonResponse({'code': 200, 'msg': '成功', 'date': notification})
    except Notification.DoesNotExist:
        return JsonResponse({'code': 404, 'msg': '未找到相关通知'})


# 发送信息
def send_notification(request):
    if request.method == 'POST':
        post_data = request.body
        data = json.loads(post_data)
        sender_id = data.get("user_id")
        send_content = data.get("send_content")
        send_time = data.get("send_time")
        recipient_id = data.get("recipient_id")
        try:
            notification = Notification.objects.create(sender_id=sender_id, send_content=send_content,
                                                       send_time=send_time, recipient_id=recipient_id)
            # serialized_notification = serializers.serialize('json', [notification])
            # deserialized_notification = json.load(serialized_notification)
            notification_data = serializers.serialize('json', notification)
            return JsonResponse({'code': 200, 'msg': '已发送', 'date': notification_data})
        except User.DoesNotExist:
            return JsonResponse({'code': 404, 'msg': '您还未登录'})
    else:
        JsonResponse({'code': 404, 'msg': '发送失败'})


# 关注用户
@csrf_exempt
def follow_user(request):
    if request.method == "POST":
        # 获取登录用户和需要关注用户
        post_data = request.body
        data = json.loads(post_data)
        user = request.session.get('userId')  # 当前登录用户的ID
        followed_user = data.get("user_id")  # 从前端获取ID
        # 查询该用户是否已经关注
        if models.Follow.objects.filter(following=user, followed=followed_user).exists():
            return JsonResponse({'code': 404, 'msg': '该用户已经在您的关注列表里面'})
        models.Follow.objects.create(following=user, followed=followed_user)
        following_count = models.Follow.objects.filter(following=user).count()
        return JsonResponse({'code': 200, 'msg': '关注成功', 'date': following_count})
    return JsonResponse({'code': 404, 'msg': '请求错误'})


# 取消关注
@csrf_exempt
def unfollow_user(request):
    if request.method == "POST":
        post_data = request.body
        data = json.loads(post_data)
        user = request.session.get('userId')  # 当前登录用户的ID
        unfollow = data.get("user_id")  # 从前端获取要取消关注的人
        models.Follow.objects.filter(following=user, followed=unfollow).delete()
        if models.Follow.objects.filter(following=user, followed=unfollow).exists():
            return JsonResponse({'code': 404, 'msg': '取消关注失败'})
        return JsonResponse({'code': 200, 'msg': '取消关注成功'})
    return JsonResponse({'code': 404, 'msg': '请求错误'})


# 更新个人信息
@csrf_exempt
def update_user_information(request):
    if request.method == "POST":
        user_id = request.session.get('userId')  # 当前登录用户的ID
        post_data = request.body
        data = json.loads(post_data)
        form = update_user_informationModelForm(data=data)
        if form.is_valid():  # 进行数据校验
            # 校验成功之后进行替换操作
            user = models.User.objects.filter(user_id=user_id).first()
            user.email = form.cleaned_data.get("email", None)
            user.user_name = form.cleaned_data.get("user_name", None)
            user.user_birthday = form.cleaned_data.get("user_birthday", None)
            user.address = form.cleaned_data.get("address", None)
            user.phone = form.cleaned_data.get("phone", None)
            user.user_age = form.cleaned_data.get("user_age", None)
            user.introduce = form.cleaned_data.get("introduce", None)
            user.save()
            return JsonResponse({'code': 200, 'msg': '修改成功'})
        return JsonResponse({'code': 404, 'msg': form.errors})
    return JsonResponse({"code": 404, 'msg': '请求错误'})


# 修改密码
@csrf_exempt
def reset_password(request):
    if request.method == "POST":
        # 确保用户已经是登录状态
        user_id = request.session.get('userId')
        post_data = request.body
        data = json.loads(post_data)
        form = alter_passwordModelForm(data=data)
        if form.is_valid():  # 执行这一步才会进行校验，因为校验不通过，是不会进入if的
            # 获取用户信息
            user = models.User.objects.filter(user_id=user_id).first()
            # 先取出通过校验的数据
            password = form.cleaned_data.get("password", None)
            password_verify = form.cleaned_data.get("password_verify", None)
            code = form.cleaned_data.get("code", None)
            code_verify = models.Code.objects.order_by("-create_time").first()  # 按倒序取出返回的第一个验证码
            # print(type(code), type(code_verify))
            # 判断验证码是否过期
            if code_verify:
                # 先检查验证码状态
                if code_verify.status == 0:
                    return JsonResponse({'code': 404, 'msg': '验证码失效'})
                create_time = code_verify.create_time
                nowTime = datetime.datetime.now()
                # print(create_time, nowTime)
                if nowTime > create_time + datetime.timedelta(minutes=5):
                    return JsonResponse({'code': 404, 'msg': '该验证码已经过期'})
            code_verify.status = 0  # 修改验证码状态
            code_verify.save()
            # 校验
            if password != password_verify:
                return JsonResponse({'code': 404, 'msg': '两次密码输入不一致'})
            if str(code) != str(code_verify):
                return JsonResponse({'code': 404, 'msg': '验证码不正确，请重新输入'})
            # 替换密码
            user.password = form.cleaned_data.get("password", None)
            user.save()
            return JsonResponse({'code': 200, 'msg': '修改成功'})
        return JsonResponse({'code': 404, 'msg': form.errors})  # 返回现存的错误
    return JsonResponse({"code": 404, 'msg': '请求错误'})
